<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车界面</title>
  <style>
    /* 整体页面样式 */
    body {
      margin: 0;
      padding: 0;
      background-image: url('img/1.png'); /* 替换为你实际的背景图链接 */
      background-size: cover;
      background-repeat: no-repeat;
      font-family: Arial, sans-serif;
    }

    /* 购物车容器样式 */
 .cart-container {
      width: 80%;
      margin: 50px auto;
      background-color: rgba(255, 255, 255, 0.8); /* 半透明白色背景，可根据喜好调整 */
      padding: 20px;
      border-radius: 10px;
    }

    /* 书籍项样式 */
 .book-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      border-bottom: 1px solid #ccc;
      padding-bottom: 10px;
    }

    /* 书籍图片样式 */
   .book-img {
      width: 100px;
      height: 150px;
      object-fit: cover;
      margin-right: 20px;
    }

    /* 书籍信息样式 */
   .book-info {
      flex: 1;
    }

    /* 数量输入框样式 */
    input[type="number"] {
      width: 50px;
      text-align: center;
    }

    /* 价格相关样式 */
   .price {
      margin-right: 10px;
    }

    /* 删除按钮样式 */
    button.delete-btn {
      background-color: #f44336;
      color: white;
      padding: 5px 10px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    /* 结算按钮样式 */
    button#checkout-btn {
      background-color: #007bff;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <div class="cart-container">
    <h2>购物车</h2>
    <div class="book-item">
      <img src="img/2.png" alt="书籍示例" class="book-img"> <!-- 替换为实际书籍图片链接 -->
      <div class="book-info">
        <h3>《哈利波特与魔法石》</h3>
        <p>作者：罗琳</p>
      </div>
      <div class="quantity-controls">
        <button class="quantity-btn" data-action="decrease">-</button>
        <input type="number" value="1" min="1" class="quantity">
        <button class="quantity-btn" data-action="increase">+</button>
      </div>
      <span class="price">单价：￥99.00</span>
      <span class="price total-price">总价：￥99.00</span>
      <button class="delete-btn">删除</button>
    </div>
    <div class="book-item">
      <img src="img/3.png" alt="另一本书籍示例" class="book-img"> <!-- 替换为实际书籍图片链接 -->
      <div class="book-info">
        <h3>《西游记》</h3>
        <p>作者：吴承恩</p>
      </div>
      <div class="quantity-controls">
        <button class="quantity-btn" data-action="decrease">-</button>
        <input type="number" value="1" min="1" class="quantity">
        <button class="quantity-btn" data-action="increase">+</button>
      </div>
      <span class="price">单价：￥129.00</span>
      <span class="price total-price">总价：￥129.00</span>
      <button class="delete-btn">删除</button>
    </div>
    <button id="checkout-btn">结算</button>
  </div>
  <script>
    // 用于存储购物车数据（以对象数组形式，每个对象表示一本书籍信息）
    let cartData = [];

    // 初始化购物车数据，从页面已有的书籍项中读取信息并存储到cartData
    function initCartData() {
      const bookItems = document.querySelectorAll('.book-item');
      bookItems.forEach(item => {
        const bookName = item.querySelector('.book-info h3').textContent;
        const author = item.querySelector('.book-info p').textContent;
        const quantity = parseInt(item.querySelector('.quantity').value);
        const unitPrice = parseFloat(item.querySelector('.price').textContent.match(/\d+\.\d+/)[0]);
        cartData.push({
          bookName,
          author,
          quantity,
          unitPrice
        });
      });
    }

    // 渲染购物车数据到页面上，更新页面显示
    function renderCart() {
      const cartContainer = document.querySelector('.cart-container');
      cartContainer.innerHTML = `
        <h2>购物车</h2>
      `;
      cartData.forEach((book, index) => {
        const bookItem = document.createElement('div');
        bookItem.className = 'book-item';
        bookItem.innerHTML = `
          <img src="img/${index + 2}.png" alt="${book.bookName}" class="book-img">
          <div class="book-info">
            <h3>${book.bookName}</h3>
            <p>${book.author}</p>
          </div>
          <div class="quantity-controls">
            <button class="quantity-btn" data-action="decrease">-</button>
            <input type="number" value="${book.quantity}" min="1" class="quantity">
            <button class="quantity-btn" data-action="increase">+</button>
          </div>
          <span class="price">单价：￥${book.unitPrice.toFixed(2)}</span>
          <span class="price total-price">总价：￥${(book.quantity * book.unitPrice).toFixed(2)}</span>
          <button class="delete-btn">删除</button>
        `;
        cartContainer.appendChild(bookItem);
      });
      addEventListeners();
    }

    // 添加事件监听器到页面元素
    function addEventListeners() {
      const bookItems = document.querySelectorAll('.book-item');
      const checkoutButton = document.getElementById('checkout-btn');

      // 为每个数量输入框添加输入事件监听器，用于实时更新总价
      bookItems.forEach(item => {
        const quantityInput = item.querySelector('.quantity');
        quantityInput.addEventListener('input', updateTotalPrice);

        const decreaseButton = item.querySelector('.quantity-btn[data-action="decrease"]');
        const increaseButton = item.querySelector('.quantity-btn[data-action="increase"]');

        decreaseButton.addEventListener('click', function () {
          let currentQuantity = parseInt(quantityInput.value);
          if (currentQuantity > 1) {
            quantityInput.value = currentQuantity - 1;
            updateTotalPrice();
          }
        });

        increaseButton.addEventListener('click', function () {
          let currentQuantity = parseInt(quantityInput.value);
          quantityInput.value = currentQuantity + 1;
          updateTotalPrice();
        });
      });

      // 为每个删除按钮添加点击事件监听器
      bookItems.forEach(item => {
        const deleteButton = item.querySelector('.delete-btn');
        deleteButton.addEventListener('click', function () {
          const bookName = item.querySelector('.book-info h3').textContent;
          removeBookFromCart(bookName);
          renderCart();
        });
      });

      // 为结算按钮添加点击事件监听器
      checkoutButton.addEventListener('click', function () {
        const totalPrice = calculateTotalPrice();
        alert('购物车总价为：￥' + totalPrice.toFixed(2));
      });
    }

    // 计算购物车中所有书籍的总价
    function calculateTotalPrice() {
      let totalPrice = 0;
      cartData.forEach(book => {
        totalPrice += book.quantity * book.unitPrice;
      });
      return totalPrice;
    }

    // 更新总价显示（当数量改变时调用）
    function updateTotalPrice() {
      const bookItems = document.querySelectorAll('.book-item');
      bookItems.forEach((item, index) => {
        const quantity = parseInt(item.querySelector('.quantity').value);
        cartData[index].quantity = quantity;
        const itemTotalPrice = quantity * cartData[index].unitPrice;
        item.querySelector('.total-price').textContent = `总价：￥${itemTotalPrice.toFixed(2)}`;
      });
    }

    // 从购物车中移除指定书籍
    function removeBookFromCart(bookName) {
      cartData = cartData.filter(book => book.bookName!== bookName);
    }

    // 页面加载时初始化购物车数据并渲染页面
    window.onload = function () {
      initCartData();
      renderCart();
    };
  </script>
</body>

</html>
